package com.hg.miaosha.order;

import com.hg.miaosha.product.ProductDO;
import com.hg.miaosha.product.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author: skh
 * @Date: 2019/10/16 15:11
 * @Description:
 */
@Service
@Slf4j
public class OrderService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private ProductService productService;

    //吞吐量:200/s
    @Transactional
    public void seckill(Integer productId,Integer amount){
        //查询商品
        ProductDO productDO =  productService.getProductByProductId(productId);
        //判断库存
        if (productDO.getStock() <= 0) {
            throw new RuntimeException("商品库存不足,秒杀失败");
        }

        //创建秒杀订单
        OrderDO orderDO = new OrderDO();
        orderDO.setProductId(productId);
        orderDO.setAmount(amount);
        this.saveOrder(orderDO);

        //减库存,通过stock>0防止超卖
        Integer updateNum = productService.reduceStock(productId,amount);
        if (updateNum <= 0) {
            throw new RuntimeException("商品库存不足,秒杀失败");
        }
        log.info("秒杀成功");
    }

    public void saveOrder(OrderDO orderDO) {
        orderDao.insert(orderDO);
    }
}
